package com.ruoyi.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * 上传图片的图片服务器,返回链接
 * @author zhoudong
 *
 */
public class UploadImgUtils {
	
	private static Logger log = LoggerFactory.getLogger(UploadImgUtils.class);
	
	/**
	 * 图片上传
	 * @param reqUrl
	 * @param filePath
	 * @return
	 */
	public static String uploadFile(String reqUrl,String filePath){
		
		String imageUrl = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		try {
			HttpPost httppost = new HttpPost(reqUrl);

			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(200000).setSocketTimeout(200000).build();
			httppost.setConfig(requestConfig);

			FileBody bin = new FileBody(new File(filePath));

			HttpEntity reqEntity = MultipartEntityBuilder.create()
					.addPart("file", bin).build();

			httppost.setEntity(reqEntity);

			log.info("executing request " + httppost.getRequestLine());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					imageUrl = EntityUtils.toString(resEntity);
					log.info("image url : "+imageUrl);
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
			}
			return imageUrl;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
